<?php

namespace app\jigou\controller\qingdongams\jigoucustomer;

use addons\qingdongams\model\Receivables;
use addons\qingdongams\model\BusinessProduct;
use addons\qingdongams\model\ContactsOther;
use addons\qingdongams\model\ContractProduct;
use addons\qingdongams\model\Quote;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\File;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\ProductPart;
use addons\qingdongams\model\Product;
use addons\qingdongams\model\QuoteProduct;
use addons\qingdongams\model\Ratio;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\WordTemplate;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\ContractOther;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\Contacts;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\OperationLog;
use addons\qingdongams\model\Record;
use addons\qingdongams\model\ContractFile;
use addons\qingdongams\model\Flow;
use addons\qingdongams\model\Business;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\TemplateProcessor;
use addons\qingdongams\model\Contract as ContractModel;
use addons\qingdongams\model\Message;
use think\Db;
use think\Exception;


/**
 * 订单管理
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
class Contract extends Base {
    protected $relationSearch = true;
    /**
     * @var \addons\qingdongams\model\Contract
     */
    protected $model = null;


    public function _initialize() {
        parent::_initialize();
        $this->model = new \addons\qingdongams\model\Contract;
    }


    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //0:全部 1：我负责的 2：下属负责的 3：今日待跟进 4:今日已跟进 5:从未跟进的
            $type = input('type',0);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            switch($type){
                case 1:
                    $staff = Staff::info();
                    $wheres['contract.owner_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['contract.owner_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                case 3:
                    $start = date('Y-m-d 00:00:00');
                    $end = date('Y-m-d 23:59:59');
                    $record = Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select();
                    $relationId = [];
                    foreach($record as $k=>$v){
//                        $whereRe['id'] = array('gt',$v['id']);
                        $whereRe['relation_id'] = $v['relation_id'];
                        $recordData = Record::where($whereRe)->count();
                        if($recordData == 0){
                            $relationId[] = $v['relation_id'];
                        }

                    }
                    $wheres['contract.id'] =  array('in',$relationId);
                    $staff = Staff::info();
                    $wheres['contract.owner_staff_id'] =  $staff->id;
                    break;
                case 4:
                    $start = date('Y-m-d 00:00:00');
                    $end = date('Y-m-d 23:59:59');
                    $record = Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',strtotime($start)),array('elt',strtotime($end)))))->field("id,relation_id")->select();
                    $relationId = [];
                    foreach($record as $k=>$v){
//                        $whereRe['id'] = array('gt',$v['id']);
                        $whereRe['relation_id'] = $v['relation_id'];
                        $recordData = Record::where($whereRe)->count();
                        if($recordData >=1){
                            $relationId[] = $v['relation_id'];
                        }

                    }
                    $wheres['contract.id'] =  array('in',$relationId);
                    $staff = Staff::info();
                    $wheres['contract.owner_staff_id'] =  $staff->id;
                    break;
                case 5:
                    $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array('neq','')))->column('relation_id'))->toArray();
                    $wheres['contract.id'] =  array('not in',$record);
                    $staff = Staff::info();
                    $wheres['contract.owner_staff_id'] =  $staff->id;
                    break;
                default:
                    $wheres['contract.owner_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $ids=[];
            $group_id=input('group_id');
            $staff_id=input('staff_id');
            if ($group_id) {//角色组
                $ids = Staff::getGroupStaffIds($group_id);
            }
            if ($staff_id) {
                $ids = $staff_id;
            }
            if ($group_id || $staff_id) {
                $wheres['contract.owner_staff_id'] = ['in', $ids];
            }
            $list = $this->model->alias("contract")->where($where)
                ->where($wheres)
                ->with([
                    'customer',
                    'orderStaff',
                    'contacts',
                    'receivables',
                ])->join("qingdongams_customer customer", "contract.customer_id=customer.id", "left")->where(array("customer.customer_type" =>"机构"))->field("contract.*")->order("contract.id", $order)->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }


        $field = FormField::getFields(FormField::CONTRACT_TYPE);
        $this->assignconfig('fields', $field);
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);


                // 表单验证
                if (($result = $this->qingdongamsValidate($params, 'Contract', 'create')) !== true) {
                    $this->error($result);
                }

                $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params);
                if ($result !== true) {
                    $this->error($result);
                }
                if(isset($params['flow_staff_ids'])){
                    if(!$params['flow_staff_ids']){
                        $this->error('请选择审批人');
                    }
                }
                $result = false;
                Db::startTrans();
                try {
                    $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);

                    if($params['product']){
                        $params['product']=json_decode($params['product'],true);
                    }
                    $result = $this->model::createContract($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $flow= Flow::getsteplist(Flow::CONTRACT_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员');
        }
        $customer_id = input('customer_id');
        if($customer_id){
            $business = Business::where(array('customer_id'=>$customer_id))->select();
        }else{
            $business = Business::getList();
        }

        $this->assign('flow',$flow);
        $this->assign('staff', Staff::getStaff());
        $this->assign('customers', Customer::getList());
        $this->assign('business', $business);
        $this->assign('customer_id', $customer_id);
        $this->assign('customer', Customer::get($customer_id));
        $this->assign('business_id', input('business_id'));
        $this->assign('staffs',     Staff::allList());
        $this->assign('form_data', Form::getDataValue('contract'));
        $this->assign('ratio',Ratio::where(['status'=>1])->select());
        $this->assign('contractNum', 'C'.date('Ymd').rand(10000,99999));
        return $this->view->fetch();
    }


    /**
     * 修改订单
     */
    public function edit($ids = null) {
        $map['id'] = $ids;
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params = $this->preExcludeFields($params);
            $row = $this->model::where(['id' => $ids, 'check_status' => ['in', [3, 4]]])->find();
            if (empty($row)) {
                $this->error('订单审核中或已审核通过无法修改');
            }
            // 表单验证
            if (($result = $this->qingdongamsValidate($params, 'Contract', 'create')) !== true) {
                $this->error($result);
            }
            $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params,$ids);
            if ($result !== true) {
                $this->error($result);
            }
            Db::startTrans();
            try {

                $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);

                $params['id']=$ids;
                $params['owner_staff_id'] = $row['owner_staff_id'];

                if($params['product']){
                    $params['product']=json_decode($params['product'],true);
                }
                $result = $this->model::updateContract($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('修改成功');
        }
        $row = $this->model->where($map)->with(['customer','contacts','business'])->find();
        if(empty($row)){
            $this->error('信息不存在');
        }
        $row = $row->toArray();
        $row = ContractOther::getOther($row);
        $product=ContractProduct::where(['contract_id'=>$ids])->with(['productinfo'])->select();

        foreach ($product as $k=>$v){
            if($v['productinfo']){
                $v['product_name']=$v['productinfo']['name'];
                $v['cost_price']=$v['productinfo']['cost_price'];
                $v['type']=$v['productinfo']['type'];
                if($v['productinfo']['goods']){
                    $v['goods_name']=$v['productinfo']['goods']['name'];
                }
            }
            $product[$k]=$v;
        }
        $row['product']=json_encode($product);
        $row['ratios']=json_decode($row['ratios'],true);
        $flow= Flow::getsteplist(Flow::CONTRACT_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员');
        }
        $this->assign('flow',$flow);
        $this->view->assign("row", $row);
        $this->assign('customers', Customer::getList());
        $this->assign('business', Business::getList());
        $this->assign('staffs', Staff::getList());
        $this->assign('staff', Staff::getStaff());
        $this->assign('ratio',Ratio::where(['status'=>1])->select());
        $this->assign('form_data', Form::getDataValue('contract',$row));
        $this->assign('contacts', Contacts::where(['customer_id'=>$row['customer_id']])->field('id,name')->select());

        return $this->view->fetch();
    }


    /**
     * 获取附件记录
     */
    public function get_file($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = ContractFile::where(['contract_id' => $ids])->with(['file'])->field('file_id')->paginate($limit);

        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

    /**
     * 订单详情
     */
    public function detail($ids = null) {
        $row = $this->model->where(['id' => $ids])->with([
            'customer',
            'contacts',
            'orderStaff',
            'ownerStaff',
            'business'
        ])->find();
        if (empty($row)) {
            $this->error(__('No Results were found'));
        }
        $row=$row->toArray();
        $row=ContractOther::getOther($row);
        $row['ratios'] = json_decode($row['ratios'], true);
        if ($row['ratios']) {
            foreach ($row['ratios'] as $k => $v) {
                $v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
                $v['money'] = $row['money'] * ($v['ratio'] / 100);
                $row['ratios'][$k] = $v;
            }
        }
        $row['repayment_money'] = Receivables::where(['contract_id'=>$ids])->sum('money'); //已回款
        $row['no_money'] = $row['money'] -$row['repayment_money'];
        if($row['no_money'] <= 0){
            $row['no_money'] = 0;
        }
        $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::CONTRACT_TYPE,$ids));
        $this->assign('flow',Flow::getstepdetail(Flow::CONTRACT_STATUS, $ids));
        //跟进记录
        $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
        //操作记录
        $log=OperationLog::getList(OperationLog::CONTRACT_TYPE, $ids);

        //标记通知已读
        Message::setRead(Message::CONTRACT_TYPE, $ids, $this->_staff->id);

        $this->assign('operation_log',$log);
        $this->assign('row', $row);
        $this->assign('ids', $ids);
        $this->assign('form_data', Form::getDataValue('contract',$row));
        $this->assignconfig("idinfo", ['id' => $ids]);
        return $this->view->fetch();
    }

    /**
     * 获取联系人select
     */
    public function get_contacts_list(){
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $ids=input('ids');
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $staff = Contacts::where($where)->where(['customer_id'=>$ids])
            ->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }

    /**
     * 获取产品明细
     */
    public function get_contract_product(){
        $contract_id=input('contract_id',0,'intval');
        if(empty($contract_id)){
            $this->error('参数不能为空');
        }
        $products=ContractProduct::where(['contract_id'=>$contract_id])
            ->with(['productinfo'])->select();
        foreach($products as $k=>$v){
            if(!$v['productinfo']['id']){
                unset($products[$k]);
            }
        }
        return json(['rows' =>$products, 'total' => count($products)]);
    }

    /**
     * 获取回款计划
     */
    public function get_receivables_plan($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = \addons\qingdongams\model\ReceivablesPlan::where([
            'contract_id' => $ids
        ])->with(['customer'])->paginate($limit);

        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }


    /**
     * 获取回款记录
     */
    public function get_receivables($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = \addons\qingdongams\model\Receivables::where([
            'contract_id' => $ids
        ])->with(['customer','ownerStaff'])->paginate($limit);

        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

    /**
     * 获取商机关联产品
     */
    public function get_business_product(){
        $business_id=input('business_id');
        if(empty($business_id)){
            $this->error('参数不能为空');
        }
        $business=BusinessProduct::where(['business_id'=>$business_id])->with(['productinfo'])->select();

        $this->success('请求成功','',$business);
    }

    /**
     * 获取产品
     */
    public function get_product()
    {
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $countrys = Product::where($where)->field('id,name')->order('id desc')->select();
        return json(['list' => $countrys, 'total' => count($countrys)]);
    }

    /**
     * 获取产品配置
     */
    public function get_product_part()
    {
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $countrys = ProductPart::where($where)->field('id,name')->order('id desc')->select();
        return json(['list' => $countrys, 'total' => count($countrys)]);
    }

    /**
     * 获取产品价格
     */
    public function get_product_price()
    {
        $id = input('id', 0);
        $price = Product::where(['id' => $id])->value('price') ?? 0;
        $this->success('请求成功', '', ['price' => $price]);
    }

    /**
     * 获取审批人列表
     */
    public function getstaff(){
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $staff = Staff::where($where)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }

    /**
     * 删除
     */
    public function del($ids = "") {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $map['id'] = array('in', $ids);
        $result = $this->model->destroy($map);
        if (!$result) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }


    /**
     * 导入订单
     * @return string|void
     */
    public function import()
    {
        set_time_limit(0);
        if ($this->request->isPost()) {

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . 'public' . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            //开始读取数据
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[$currentRow][] = $val;
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
            }
            if (!isset($fields[1])) {
                $this->error('导入文件第一行没有数据');
            }
            $lastid = $this->model->withTrashed()->order('id desc')->value('id');

            $lastid = $lastid + 5;//防止重复

            $contractRow = [];
            $errorInfo = [];

            $fieldnames = FormField::where(['types' => FormField::CONTRACT_TYPE])->column('field', 'name');
            if(!$fieldnames){
                $this->error('请在系统管理->字段管理中保存订单管理表单生成订单导入字段');
            }
            $customerNames=Customer::where([])->column('id,owner_staff_id','name');
            $contacts = Contacts::where([])->field('id,name,customer_id')->select();
            $contacts = collection($contacts)->toArray();
            $contactsNames = [];
            foreach ($contacts as $v) {
                $contactsNames[$v['customer_id']][$v['name']] = $v;
            }
            $businessNames=Business::where([])->column('id','name');
            $staffNames=Staff::where([])->column('id','name');
            $fn = [];
            $nums=$this->model->where([])->column('num');
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                foreach ($values as $l) {

                    $fn[] = $fieldnames[$l] ?? '';
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
                $lastid++;
                $addContract = ['id' => $lastid];
                $customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0;
                if(empty($customer)){
                    $errorInfo[] = "第{$currentRow}行，客户名称不存在;";
                    continue;
                }
                $addContract['customer_id']=$customer['id'];
                $addContract['owner_staff_id']=$customer['owner_staff_id'];
                $addContract['create_staff_id']=$customer['owner_staff_id'];

                $contacts = isset($contactsNames[$addContract['customer_id']])?(isset($contactsNames[$addContract['customer_id']][$values[1]]) ? $contactsNames[$addContract['customer_id']][$values[1]] : []):[];
                if (!empty($values[1]) && empty($contacts)) {
                    $errorInfo[] = "第{$currentRow}行，客户签约人名称不存在;";
                    continue;
                }
                $addContract['contacts_id']=$contacts['id']??0;
                $business=isset($businessNames[$values[2]])?$businessNames[$values[2]]:[];
                if (!empty($values[2]) && empty($business)) {
                    $errorInfo[] = "第{$currentRow}行，商机名称不存在;";
                    continue;
                }
                $addContract['business_id']=$business['id']??0;
                $orderstaff=isset($staffNames[$values[3]])?$staffNames[$values[3]]:[];
                if (!empty($values[3]) && empty($orderstaff)) {
                    $errorInfo[] = "第{$currentRow}行，商机名称不存在;";
                    continue;
                }
                $addContract['order_staff_id']=$orderstaff['id']??0;

                foreach ($values as $kv => $value) {
                    if (!isset($fn[$kv]) || empty($fn[$kv])) {
                        continue;
                    }
                    $addContract[$fn[$kv]] = $value;
                }
                if (empty($addContract['num'])) {
                    $errorInfo[] = "第{$currentRow}行，订单编号不能为空;";
                    continue;
                }
                if (in_array($addContract['num'], $nums)) {
                    $errorInfo[] = "第{$currentRow}行，订单编号`{$addContract['num']}`已存在;";
                    continue;
                }
                if (empty($addContract['name'])) {
                    $errorInfo[] = "第{$currentRow}行，订单名称不能为空;";
                    continue;
                }
                $contractRow[] = $addContract;
            }
            if (!empty($errorInfo)) {
                $this->error(implode(',', $errorInfo));
            }
            Db::startTrans();
            try {
                $this->model::importContract($contractRow);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('导入成功');
        }
        $this->assign('staffs', Staff::getList());
        return $this->view->fetch();
    }

    /**
     * 模板
     */
    public function template()
    {
        $title = [
            '客户名称',
            '客户签约人',
            '商机名称',
            '公司签约人',

        ];
        $contractData = Form::getDataValue(Form::CONTRACT_TYPE);

        foreach ($contractData as $val) {
            $title[] = $val['config']['label'];
        }

        $file = export_excel($title, [], '订单');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $file['fileName']);
        header('Cache-Control: max-age=0');

        $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('导出文件'); //设置标题
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('导出文件');
        /* 循环读取每个单元格的数据 */
        $a = 'A';
        $currentSheet = $obj->getActiveSheet();
        foreach ($title as $key => $value) {
            //读取工作表1
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
            //这里是设置单元格的内容
            $currentSheet->getCell($a . '1')->setValue($value);
            $a++;
        }

        $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);

        $PHPWriter->save('php://output');
    }

    /**
     * 导出信息
     */
    public function export()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $isall = input('isall');
        $wheres = array();
        //导出其中几条
        if (isset($ids)) {
            $wheres['id'] = array('in', $ids);
        }
        //导出全部
        if (isset($isall)) {
            if ($isall == 3) {
                unset($wheres['id']);
            }
        }
        //0:全部 1：我负责的 2：下属负责的 3：今日待跟进 4:今日已跟进 5:从未跟进的
        $type = input('type',0);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        switch($type){
            case 1:
                $staff = Staff::info();
                $wheres['owner_staff_id'] =  $staff->id;
                break;
            case 2:
                $wheres['owner_staff_id'] =  array('in',Staff::getLowerStaffId());
                break;
            case 3:
                $start = date('Y-m-d 00:00:00');
                $end = date('Y-m-d 23:59:59');
                $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
                $relationId = [];
                foreach($record as $k=>$v){
                    $whereRe['id'] = array('gt',$v['id']);
                    $whereRe['relation_id'] = $v['relation_id'];
                    $recordData = Record::where($whereRe)->count();
                    if($recordData == 0){
                        $relationId[] = $v['relation_id'];
                    }

                }
                $wheres['id'] =  array('in',$relationId);
                $staff = Staff::info();
                $wheres['owner_staff_id'] =  $staff->id;
                break;
            case 4:
                $start = date('Y-m-d 00:00:00');
                $end = date('Y-m-d 23:59:59');
                $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array(array('egt',$start),array('elt',$end))))->field("id,relation_id")->select())->toArray();
                $relationId = [];
                foreach($record as $k=>$v){
                    $whereRe['id'] = array('gt',$v['id']);
                    $whereRe['relation_id'] = $v['relation_id'];
                    $recordData = Record::where($whereRe)->count();
                    if($recordData >=1){
                        $relationId[] = $v['relation_id'];
                    }

                }
                $wheres['id'] =  array('in',$relationId);
                $staff = Staff::info();
                $wheres['owner_staff_id'] =  $staff->id;
                break;
            case 5:
                $record = collection(Record::where(array('relation_type'=>3,'next_time'=>array('neq','')))->column('relation_id'))->toArray();
                $wheres['id'] =  array('not in',$record);
                $staff = Staff::info();
                $wheres['owner_staff_id'] =  $staff->id;
                break;
            default:
                $wheres['owner_staff_id'] =  array('in',Staff::getMyStaffIds());
                break;

        }

        $list = $this->model->with([
            'customer',
            'orderStaff',
            'contacts',
            'ownerStaff','contractOther',
        ])->where($where)->where($wheres)->order($sort, $order)->select();
        $list = collection($list)->toArray();

        if (!$list) {
            $this->error('无导出数据');
        }
        $title = [
            '序号',
            '客户名称',
            '客户签约人',
            '公司签约人',
            '归属人',
            '创建时间',
        ];

        $dataValue = Form::getDataValue(Form::CONTRACT_TYPE);

        foreach ($dataValue as $val) {
            $title[] = $val['config']['label'];
        }
        foreach ($list as $k => $v) {
            if($v['contract_other']){//其他客户
                $other=$v['contract_other']['otherdata'];
                $other=json_decode($other,true);
                $v = array_merge($v, $other);
            }
            $field = array(
                $v['id'],
                $v['customer']['name'],
                $v['contacts']['name']??'',
                $v['order_staff']['name']??'',
                $v['owner_staff']['name']??'',
                $v['createtime'],
            );
            foreach ($dataValue as $val) {
                if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
                    $field[] = $v[$val['id'] . '_str'] ?? '';
                } else {
                    $field[] = ($v[$val['id']] ?? '');
                }
            }
            $data[] = $field;
        }
        $file = export_excel($title, $data, '订单');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }

    /**
     * 导入产品明细
     * @return string|void
     */
    public function import_product()
    {
        set_time_limit(0);
        if ($this->request->isPost()) {

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . 'public' . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            //开始读取数据
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[$currentRow][] = $val;
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? '' : trim($val);
                }
            }
            if (!isset($fields[1])) {
                $this->error('导入文件第一行没有数据');
            }

            $lastid = ContractProduct::order('id desc')->value('id');

            $lastid = $lastid + 5;//防止重复

            $contractProductRow = [];
            $errorInfo = [];

            $contractNum=$this->model::where([])->column('id,name','num');
            $productName=Product::where([])->column('id,price','name');
            $fn = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
                $lastid++;
                $addContractProduct = ['id' => $lastid];
                $contract = isset($contractNum[$values[0]]) ? $contractNum[$values[0]] : 0;
                if (empty($contract)) {
                    $errorInfo[] = "第{$currentRow}行，订单编号不存在;";
                    continue;
                }
                $product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0;
                if (empty($product)) {
                    $errorInfo[] = "第{$currentRow}行，产品名称不存在;";
                    continue;
                }
                if (empty($values[2])) {
                    $errorInfo[] = "第{$currentRow}行，产品数量不能为空;";
                    continue;
                }
                if (empty($values[3])) {
                    $errorInfo[] = "第{$currentRow}行，产品售价不能为空;";
                    continue;
                }
                $addContractProduct['contract_id'] = $contract['id'];
                $addContractProduct['product_id'] = $product['id'];
                $addContractProduct['number'] = $values[2];
                $addContractProduct['price'] = $values[3];
                $contractProductRow[]=$addContractProduct;
            }
            if (!empty($errorInfo)) {
                $this->error(implode(',', $errorInfo));
            }
            Db::startTrans();
            try {
                ContractProduct::importProduct($contractProductRow);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('导入成功');
        }
        $this->assign('staffs', Staff::getList());
        return $this->view->fetch();
    }

    /**
     * 模板
     */
    public function template_product()
    {
        $title = [
            '订单编号',
            '商品名称',
            '数量',
            '售价',
        ];

        $file = export_excel($title, [], '产品明细');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $file['fileName']);
        header('Cache-Control: max-age=0');

        $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('导出文件'); //设置标题
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('导出文件');
        /* 循环读取每个单元格的数据 */
        $a = 'A';
        $currentSheet = $obj->getActiveSheet();
        foreach ($title as $key => $value) {
            //读取工作表1
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
            //这里是设置单元格的内容
            $currentSheet->getCell($a . '1')->setValue($value);
            $a++;
        }

        $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);

        $PHPWriter->save('php://output');
    }

    /**
     * 导出信息
     */
    public function export_product()
    {
        $ids = input('ids');
        $type = input('type');
        $wheres = array();
        //导出其中几条
        if (isset($ids)) {
            $wheres['contract_id'] = array('in', $ids);
        }
        //导出全部
        if (isset($type)) {
            if ($type == 3) {
                unset($wheres['contract_id']);
            }
        }

        $list=ContractProduct::where($wheres)->with(['contract','productinfo'])->select();
        $list = collection($list)->toArray();

        if (!$list) {
            $this->error('无导出数据');
        }
        $title = [
            '序号',
            '订单编号',
            '订单名称',
            '商品名称',
            '售价',
            '批发价',
            '产品',
            '规格',
            '数量',
        ];
        $data=[];
        foreach ($list as $k => $v) {

            $field = array(
                $v['id'],
                $v['contract']['num'],
                $v['contract']['name'],
                $v['productinfo']['name']??'',
                $v['price']??'',
                $v['productinfo']['cost_price']??'',
                $v['productinfo']['goods']['name']??'',
                $v['productinfo']['unit']??'',
                $v['number']??'',
            );
            $data[] = $field;
        }
        $file = export_excel($title, $data, '产品明细');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }


    /**
     * 导出word
     */
    public function words($ids = null)
    {
        if ($this->request->isPost()) {
            $file = input('file', '');
            $is_template=input('is_template',0);
            $template_name=input('template_name','');
            if (empty($file)) {
                $this->error('导出模板');
            }
            if($is_template == 1){
                if(empty($template_name)){
                    $this->error('模板名称不能为空');
                }
                $create=[
                    'type'=>'contract',
                    'name'=>$template_name,
                    'url'=>$file
                ];
                $wordTemplateModel = new WordTemplate();
                $wordTemplateModel->save($create);
            }
            $tmp = new TemplateProcessor('.' . $file);
            Settings::setCompatibility(true);
            Settings::setOutputEscapingEnabled(true);

            $row = $this->model->where(['id'=>$ids])->with(['customer','contacts','business','orderStaff'])->find();
            $row = $row->toArray();
            $row = ContractOther::getOther($row);

            $form = Form::getDataValue(Form::CONTRACT_TYPE);
            $imgNames=[];
            foreach($form as $k=>$v){
                if($v['component'] == 'uploadImage'){
                    $imgNames[]=$v['id'];
                }
            }
            foreach ($row as $key => $item) {

                if(in_array($key,$imgNames) && $item ){
                    if(is_array($item)){
                        foreach ($item as $it){
                            $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
                        }
                    }else{
                        $fileinfo = File::where(['id'=>['in',$item]])->field('id,name,file_path,save_name')->select();
                        foreach ($fileinfo as $it){
                            $tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
                        }
                    }
                }else{
                    if(is_array($item)){
                        $tmp->setValue($key , '');//
                        continue;
                    }
                    $tmp->setValue($key , $item);//
                }
            }
            $contractProduct=ContractProduct::where(['contract_id'=>$ids])
                ->with(['productinfo'])->select();
            $contractProduct=collection($contractProduct)->toArray();
            $c = count($contractProduct);//总行数
            $tmp->cloneRow('product_name', $c);//复制行
            for ($i = 0; $i < $c; $i++) {
                $p=$contractProduct[$i];
                $tmp->setValue("product_name#" . ($i + 1), $p['productinfo']['name'] ?? '');//名称
                $tmp->setValue("product_unit#" . ($i + 1), $p['productinfo']['unit'] ?? '');//单位
                $tmp->setValue("product_num#" . ($i + 1), $p['productinfo']['num'] ?? '');//编码
                $tmp->setValue("product_type#" . ($i + 1), $p['productinfo']['type'] ?? '');//规格
                $tmp->setValue("product_number#" . ($i + 1), $p['number']);//数量
                $tmp->setValue("product_price#" . ($i + 1), $p['price']);//总价格
                $tmp->setValue("product_total#" . ($i + 1), $p['price'] * $p['number']);//总价格
            }

            $tmp->setValue('money_big', convertAmountToCn($row['money']));
            $tmp->setValue('customer_name', $row['customer']['name'] ?? '');
            $tmp->setValue('contacts_name', $row['contacts']['name'] ?? '');
            $tmp->setValue('business_name', $row['business']['name'] ?? '');
            $tmp->setValue('order_staff_name', $row['order_staff']['name'] ?? '');
            //end 配置
            $filename = $row['name'];
            $filepath = $filename . '.docx';
            $fileurl = './uploads/' . date('Ymd') . '/';
            if (!file_exists($fileurl)) {
                mkdir($fileurl);
            }
            $tmp->saveAs($fileurl . $filepath);//另存为
            $model = new File();
            $data = [
                'types' => 'file',
                'name' => $filepath,
                'save_name' => $fileurl . $filepath,
                'size' => filesize($fileurl . $filepath),
                'file_path' => trim($fileurl, '.') . $filepath,
            ];
            $model->save($data);
            $lastid = $model->id;
            $file = cdnurl($model::getUrl($lastid), true);

            $this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filepath]);
        }

        $templates=WordTemplate::where(['type'=>'contract'])->select();
        $contract = Form::getDataValue(Form::CONTRACT_TYPE);
        $columns = array();
        $columns[] = ['key' => 'customer_name', 'name' => '客户名称'];
        $columns[] = ['key' => 'contacts_name', 'name' => '联系人名称'];
        $columns[] = ['key' => 'business_name', 'name' => '商机名称'];
        $columns[] = ['key' => 'order_staff_name', 'name' => '公司签约人名称'];
        $columns[] = ['key' => 'money_big', 'name' => '订单金额人民币大写'];
        foreach ($contract as $k => $v) {
            $columns[] = array(
                'key' => $v['id'],
                'name' => $v['config']['label'],
            );
        }

        $columns[] = ['key' => 'product_name', 'name' => '产品名称'];
        $columns[] = ['key' => 'product_unit', 'name' => '产品单位'];
        $columns[] = ['key' => 'product_num', 'name' => '产品编码'];
        $columns[] = ['key' => 'product_type', 'name' => '产品规格'];
        $columns[] = ['key' => 'product_number', 'name' => '产品数量'];
        $columns[] = ['key' => 'product_price', 'name' => '产品单价'];
        $columns[] = ['key' => 'product_total', 'name' => '产品合计'];

        $this->assign('column', $columns);
        $this->assign('templates', $templates);
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 报价单转为订单
     */
    public function quote_change()
    {
        $quote_id = input('quote_id');

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);


                // 表单验证
                if (($result = $this->qingdongamsValidate($params, 'Contract', 'create')) !== true) {
                    $this->error($result);
                }

                $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params);
                if ($result !== true) {
                    $this->error($result);
                }
                $result = false;
                Db::startTrans();
                try {
                    $params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);

                    if ($params['product']) {
                        $params['product'] = json_decode($params['product'], true);
                    }
                    $result = $this->model::createContract($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $flow = Flow::getsteplist(Flow::CONTRACT_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员');
        }
        $customer_id = input('customer_id');
        if ($customer_id) {
            $business = Business::where(array('customer_id' => $customer_id))->select();
        } else {
            $business = Business::getList();
        }

        $quote = Quote::where(['id' => $quote_id])->with(['customer','contacts'])->find();
        $product=QuoteProduct::where(['quote_id'=>$quote['id']])->with(['productinfo'])->select();

        foreach ($product as $k=>$v){
            if($v['productinfo']){
                $v['product_name']=$v['productinfo']['name'];
                $v['cost_price']=$v['productinfo']['cost_price'];
                $v['type']=$v['productinfo']['type'];
                if($v['productinfo']['goods']){
                    $v['goods_name']=$v['productinfo']['goods']['name'];
                }
            }
            $product[$k]=$v;
        }
        $quote['product']=json_encode($product);
        $quote['num']=getItemNumber('contract');
        $quote['money']=$quote['quote_amount'];

        $this->assign('row', $quote);

        $this->assign('flow', $flow);
        $this->assign('staff', Staff::getStaff());
        $this->assign('customers', Customer::getList());
        $this->assign('business', $business);
        $this->assign('customer_id', $customer_id);
        $this->assign('business_id', input('business_id'));
        $this->assign('staffs', Staff::allList());
        $this->assign('form_data', Form::getDataValue('contract'));
        $this->assign('ratio', Ratio::where(['status' => 1])->select());


        return $this->view->fetch();
    }

    /**下载订单
     */
    public function download_quote($id = null)
    {
        $contract = ContractModel::where(['id' => $id])->with(['customer', 'contacts','orderStaff',])->find();
        if (empty($contract)) {
            $this->error('不能为空');
        }

        $contract = $contract->toArray();

        $contractProduct = ContractProduct::where(['contract_id' => $id])->with(['product'])->select();
        $tmp = new TemplateProcessor('assets/addons/qingdongams/phpword/contract.docx');
        \PhpOffice\PhpWord\Settings::setCompatibility(true);
        \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);


        $tmp->setValue('number', $contract['num']);//订单编号
        $tmp->setValue('name', $contract['customer']['name']);//乙方
        $tmp->setValue('signing_time', date('Y年m月d日', strtotime($contract['order_date'])));//签订时间
        $tmp->setValue('signed_at', $contract['signed_at']);//签订地点
        $tmp->setValue('order_name', $contract['order_staff']['name']);
        $tmp->setValue('order_mobile', $contract['order_staff']['mobile']);
        $rows = count($contractProduct);//总行数
        $tmp->cloneRow('one', $rows);//复制行

        for ($i = 0; $i < $rows; $i++) {
            $tmp->setValue("one#" . ($i + 1), $contractProduct[$i]['name'] ?? '');//名称
            $tmp->setValue("two#" . ($i + 1), $contractProduct[$i]['num'] ?? '');//型号
            $tmp->setValue("three#" . ($i + 1), $contractProduct[$i]['number'] ?? '');//数量
            $tmp->setValue("four#" . ($i + 1), $contractProduct[$i]['price'] ?? '');//总价格
        }

        //start 配置
        $configs = [];


        $tmp->setValue("discount_rate", $contract['discount_rate']);//金额
        $tmp->setValue("price", $contract['money']);//金额
        $tmp->setValue("price_big", convertAmountToCn($contract['money'] ?? 0));//汉字金额
        $tmp->setValue("remarks", $contract['remarks']);//备注
        $tmp->setValue("payment", $contract['payment']);//支付方式
        $tmp->setValue("be_overdue", $contract['be_overdue']);//到期条款
        $tmp->setValue("delivery_time", $contract['delivery_time']);//
        $tmp->setValue("account", $contract['collection_account']);//
        $tmp->setValue("account_name", $contract['collection_deposit']);//
        $tmp->setValue("bank_name", $contract['collection_name']);//
        $tmp->setValue("effective", $contract['effective']);//
        $tmp->setValue("guarantee", $contract['guarantee']);//
        $tmp->setValue("address", $contract['customer']['address']);//
        $tmp->setValue("legal", $contract['legal']);//
        $tmp->setValue("entrust", $contract['entrust']);//
        $tmp->setValue("handler", $contract['handler']);//
        $tmp->setValue("mobile", $contract['mobile']);//
        $tmp->setValue("fax", $contract['fax']);//
        $tmp->setValue("deposit", $contract['deposit']);//
        $tmp->setValue("y_account", $contract['account']);//
        //end 配置
        $filename = $contract['customer']['name'] . $contract['num'] . '.docx';
        $fileurl = './uploads/' . date('Ymd') . '/';
        if (!file_exists($fileurl)) {
            mkdir($fileurl);
        }

        $tmp->saveAs($fileurl . $filename);//另存为


        $model = new File();
        $data = [
            'types' => 'file',
            'name' => $filename,
            'save_name' => $fileurl . $filename,
            'size' => filesize($fileurl . $filename),
            'file_path' => trim($fileurl, '.') . $filename,
        ];

        $model->save($data);
        $lastid = $model->getLastInsID();
        $file = cdnurl($model::getUrl($lastid), true);

        $this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filename]);
    }
    /**
     * 添加收货地址
     */
    public function address($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $row = ContractModel::where(['id' => $ids])->find();
            if (empty($row)) {
                $this->error('订单信息不存在');
            }
            $params['id'] = $ids;
            Db::startTrans();
            try {
                ContractModel::updateContractAddress($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('添加收货地址信息成功');
        }
        $row = $this->model->where(['id' => $ids])->find();
        $this->view->assign("row", $row);
        $this->view->assign("id", $ids);
        return $this->view->fetch();
    }

    /**
     * 发票物流
     */
    public function invoice_contract($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $row = ContractModel::where(['id' => $ids])->find();
            if (empty($row)) {
                $this->error('订单信息不存在');
            }
            $params['id'] = $ids;
            Db::startTrans();
            try {
                $params['invoice_file_ids'] = File::getId($params['invoice_file_ids']);
                ContractModel::invoiceContract($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('添加收货地址信息成功');
        }
        $row = $this->model->where(['id' => $ids])->find()->toArray();
        $row['invoice_file_ids'] = implode(',', $row['invoice_file_ids']);
        $this->view->assign("row", $row);
        $this->view->assign("id", $ids);
        return $this->view->fetch();
    }

    /**
     * 发票回执单
     */
    public function receipt_contract($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            if (empty($params['receipt_file_ids'])) {
                $this->error('回执单不能为空');
            }
            if (empty($params['receipt_date'])) {
                $this->error('回执时间不能为空');
            }

            Db::startTrans();
            try {
                $params['id'] = $ids;
                $params['receipt_file_ids'] = File::getId($params['receipt_file_ids']);
                ContractModel::receiptContract($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('回执成功');
        }
        $row = $this->model->where(['id' => $ids])->find()->toArray();
        $row['receipt_file_ids'] = implode(',', $row['receipt_file_ids']);
        $this->view->assign("row", $row);
        $this->view->assign("id", $ids);
        return $this->view->fetch();

    }


    /**
     * 终止订单
     */
    public function revoke_contract()
    {
        $id = input('id');
        $model = new ContractModel();
        $row = $model->get($id);
        if (empty($row)) {
            $this->error('信息不存在');
        }
        $files = $model->where(['id' => $id])->update(['contract_status' => 2, 'check_status' => 9]);
        OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '终止订单');
        $this->success('操作成功', $files);
    }
    //即将到期的订单 默认提前三天
    public function before_over(){
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $starttime = date('Y-m-d 23:59:59');
        $endtime = date("Y-m-d 00:00:00", strtotime("-3 day"));
        $wheres['order_staff_id'] =  array('in',Staff::getMyStaffIds());
        $wheres['check_status'] = 2;
        $wheres['end_time'] = array(array('egt',$endtime),array('elt',$starttime));
        $list = $this->model->where($where)
            ->where($wheres)
            ->with([
                'customer',
                'orderStaff',
                'contacts',
                'receivables',
            ])->order($sort, $order)->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

}
